<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<button id="but">按钮</button>
<button id="bu1t">关闭</button>
<button id="bu2t">重新连接</button>
</body>
<script>
    function extracted() {
        let webSocket = new WebSocket("ws://localhost:81/ws/1");

        //建立链接
        webSocket.onopen = function () {
            console.log('建立链接')
            console.log('webSocket.readyState:' + webSocket.readyState)
        }

        //收到消息是
        webSocket.onmessage = function (evt) {
            console.log(evt.data)
            if (evt.data != null) {
                alert(evt.data)
            }
        }

        //断开连接是
        webSocket.onclose = function () {
            console.log('断开连接')
            console.log('webSocket.readyState:' + webSocket.readyState)
        }
        return webSocket;
    }

    let webSocket = extracted();

    //发送
    document.getElementById("but").addEventListener('click', () => {
        console.log("发送消息")
        webSocket.send(123)
    })
    //主动关闭
    document.getElementById("bu1t").addEventListener('click', () => {
        console.log("主动端口")
        webSocket.close()
        console.log('webSocket.readyState:' + webSocket.readyState)
    })
    //重新连接
    document.getElementById("bu2t").addEventListener('click', () => {
        console.log("重新连接")
        webSocket = extracted();
        console.log('webSocket.readyState:' + webSocket.readyState)
    })


</script>

</html>